package com.volunteer.util;

import com.volunteer.config.RedisComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * servletUtil类
 *
 * @author willow
 * @version v.0.1
 * @date 2018年08月2日
 */
@Component
public class ServletUtil {

    @Autowired
    private RedisComponent redisComponent;

    /**
     * 从Header中获得sid
     */
    public static String getSid(HttpServletRequest request) throws ErrorException {
        String header = request.getHeader(Constants.VOLUNTEER_AUTH);
        // 判断是否获得正确的sid
        if (header == null)
            throw ErrorException.USER_NOT_LOGGED_IN_EXCEPTION;
        if (header.length() != Constants.SESSION_ID_SIZE)
            throw ErrorException.USER_NOT_LOGGED_IN_EXCEPTION;
        return header;
    }

    /**
     * 创建登陆的session
     */
    public String createSessionId(Long userId) {
        // 获取随机字符，作为key
        String sid = Util.random(Constants.SESSION_ID_SIZE);
        sid = Constants.REDIS_USER_LOGIN + sid;
        // 存入redis中
        redisComponent.putString(sid, userId.toString(), Constants.TENDAYS_MINUTES, TimeUnit.MINUTES);
        // 返回key
        return sid;
    }

    /**
     * 获取requset中的sid
     * 根据sid从redis里获取userId
     * 如取不到userId,则抛出异常
     */
    public Long getUserIdbyRequestInRedis(HttpServletRequest request) throws ErrorException {
        // 获取requset中的sid
        String sid = getSid(request);
        // 根据sid从redis里获取userId并且返回userId
        return getUserIdbySidInRedis(sid);
    }

    /**
     * 根据sid从redis里获取userId
     * 如取不到userId,则抛出用户未登录异常
     */
    private Long getUserIdbySidInRedis(String sid) throws ErrorException {
        // sid为空时，抛出用户未登录异常
        if (sid == null)
            throw ErrorException.USER_NOT_LOGGED_IN_EXCEPTION;
        try {
            // 在redis中查找userId
            String userId = redisComponent.getString(sid);
            // redis中找不到userId时，抛出用户未登录异常
            if (userId == null)
                throw ErrorException.USER_NOT_LOGGED_IN_EXCEPTION;
            // 返回userId
            return Long.parseLong(userId);
        } catch (Exception ex) {
            // 抛出用户未登录异常
            throw ErrorException.USER_NOT_LOGGED_IN_EXCEPTION;
        }
    }
}
